import random

import MySQLdb
from django.shortcuts import render, redirect
from django.db import models
from . import forms
from . import models
from django.contrib import messages
import psutil
import random

from django.http import JsonResponse
from django.shortcuts import render
from .middleware import RequestCountMiddleware

import datetime
import os
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from joblib import dump, load

import sys
from django.contrib.auth.models import User
from django.core.files.storage import FileSystemStorage
from django.http import HttpResponse

from django.db import transaction
from django.core.paginator import Paginator

userpwd = "84276770"
# Create your views here.
def index(request):
    pass
    return render(request ,'index.html')

def initial(request):
    request.session['automation_level'] = 'low'
    request.session['decision_making'] = "ml_based"
    request.session['ml_algorithm'] = "SVM"
    return render(request ,'initial.html')

def aisys(request):
    request.session['automation_level'] = 'low'
    request.session['decision_making'] = "ml_based"
    request.session['ml_algorithm'] = "SVM"
    return render(request ,'aisys.html')

def login(request):
    if request.method == "POST":
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        if username and password:  # 确保用户名和密码都不为空
            username = username.strip()
            password = password.strip()
            # 用户名字符合法性验证
            # 密码长度验证
            # 更多的其它验证.....
            try:
                user = models.User.objects.get(name=username)
            except:
                messages.error(request, '用户名不正确')
                return render(request, 'login.html')
            if user.password == password:
                return redirect('/aisys/')
            else:
                messages.error(request, '密码不正确')
                return render(request, 'login.html')

    return render(request, 'login.html')

def mlogin(request):
    if request.method == "POST":
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        if username and password:  # 确保用户名和密码都不为空
            username = username.strip()
            password = password.strip()
            # 用户名字符合法性验证
            # 密码长度验证
            # 更多的其它验证.....
            try:
                user = models.User.objects.get(name=username)
                if user.name == "123456":
                    if user.password == password:
                        request.session['user_name'] = user.name
                        return redirect('../initial/')
                    else:
                        messages.error(request, '管理员密码不正确')
                        return render(request, 'mlogin.html')
            except:
                messages.error(request, '管理员用户名不正确')
                return render(request, 'mlogin.html')
    return render(request, 'mlogin.html')

def register(request):
    if request.method == "POST":
        register_form = forms.RegisterForm(request.POST)
        if register_form.is_valid():  # 获取数据
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            if password1 != password2:  # 判断两次密码是否相同
                messages.error(request, '两次输入的密码不同！')
                return render(request, 'register.html', locals())
            else:
                same_name_user = models.User.objects.filter(name=username)
                if same_name_user:  # 用户名唯一
                    messages.error(request, '用户已经存在，请重新选择用户名！')
                    return render(request, 'register.html', locals())

                # 当一切都OK的情况下，创建新用户
                new_user = models.User()
                new_user.name = username
                new_user.password = password1
                new_user.save()
                return redirect('/login/')  # 自动跳转到登录页面
    register_form = forms.RegisterForm()
    return render(request, 'register.html', locals())

def efflog(request):
    conn = MySQLdb.connect(host="localhost", user="root", passwd=userpwd, db="project", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("SELECT LogID,LogType,OccurTime,SourceIP,userID,Content,Level,RelatedID,Status,Handler,HandleTime FROM sims_efflog")
        efflog = cursor.fetchall()
    return render(request, 'efflog.html', {'efflog': efflog})


def sysdata(request):
    conn = MySQLdb.connect(host="localhost", user="root", passwd=userpwd, db="project", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute("SELECT CPUusage,MEMusage,request FROM sims_sysdata")
        sysdata = cursor.fetchall()
    cpu = psutil.cpu_percent(interval=1)
    memory = psutil.virtual_memory().percent
    disk = psutil.disk_usage('/').percent
    network = random.randint(10, 30)
    temp = random.randint(40, 90)

    automation_level = request.session.get('automation_level')
    decision_making = request.session.get('decision_making')
    ml_algorithm = request.session.get('ml_algorithm')

    y_pred_new = ''
    if ml_algorithm == 'Bayes':
        start_time = datetime.datetime.now()
        self_test = [str(start_time), str(cpu), str(memory), str(disk), str(network), str(temp)]
        self_test = pd.DataFrame([self_test], columns=['timestamp', 'cpu', 'memory', 'disk', 'network', 'temperature'])
        loaded_model = load('multinomial_nb_model.joblib')
        vectorizer = load('vectorizer.joblib')
        self_test_vectorized = vectorizer.transform(self_test.astype(str).agg(' '.join, axis=1))
        y_pred_new = loaded_model.predict(self_test_vectorized)
    elif ml_algorithm == 'SVM':
        self_test = [str(cpu), str(memory), str(disk), str(network), str(temp)]
        loaded_model = load('svm_model.pkl')
        label_encoder = load('label_encoder_SVM.pkl')
        self_test = pd.DataFrame([self_test], columns=['cpu', 'memory', 'disk', 'network', 'temperature'])
        y_pred_dt = loaded_model.predict(self_test)
        y_pred_new = label_encoder.inverse_transform(y_pred_dt)
    else:
        self_test = [str(cpu), str(memory), str(disk), str(network), str(temp)]
        loaded_model = load('decision_tree_model.pkl')
        label_encoder = load('label_encoder_de.pkl')
        self_test = pd.DataFrame([self_test], columns=['cpu', 'memory', 'disk', 'network', 'temperature'])
        y_pred_dt = loaded_model.predict(self_test)
        y_pred_new = label_encoder.inverse_transform(y_pred_dt)

    reason = ''
    action1 = '1、限制CPU使用。\n2、限制内存使用'
    action2 = '1、解锁CPU使用。\n2、解锁内存使用'
    action3 = '1、使用writeback模式。\n2、使用缓存技术'
    action4 = '1、建议关闭进程。\n2、检查散热系统'
    action5 = '1、采用云端防护。\n2、使用缓存技术'

    if y_pred_new == 'High CPU and memory usage causing system slowdowns.':
        reason = '1、能是资源密集型应用运行导致的。\n2、后台进程过多或内存泄漏'
        action = action1
    elif y_pred_new == 'High CPU and disk usage may lead to performance degradation.':
        reason = '1、磁盘密集型操作，如大文件读写。\n2、应用程序频繁的 I/O 操作。'
        action = action3
    elif y_pred_new == 'Memory and network usage critical, check for data leaks.':
        reason = '1、数据泄漏或大量数据传输。\n2、网络应用程序负载过高。'
        action = action2
    elif y_pred_new == 'Disk usage and temperature high, possible overheating.':
        reason = '1、长时间高负载文件操作。\n2、硬盘可能过热，需检查散热。'
        action = action4

    elif y_pred_new == 'Network congestion and high temperature, monitor closely.':
        reason = '1、网络拥堵可能导致设备温度升高。\n2、设备通风不良或网络硬件问题。'
        action = action4
    elif y_pred_new == 'CPU usage too high, potential bottleneck.':
        reason = '1、处理密集型任务或进程。\n2、系统优化不佳或恶意软件。'
        action = action3
    elif y_pred_new == 'Memory usage too high, possible memory leak.':
        reason = '1、内存泄漏或未优化的应用程序。\n2、多任务处理导致的资源占用。'
        action = action2
    elif y_pred_new == 'Disk usage too high, check for disk space.':
        reason = '1、磁盘空间不足或频繁的磁盘访问。\n2、文件系统碎片或备份操作。'
        action = action3
    elif y_pred_new == 'Network bandwidth critical, possible congestion.':
        reason = '1、网络带宽不足或过多的连接请求。\n2、分布式拒绝服务攻击（DDoS）。'
        action = action5
    elif y_pred_new == 'Critical temperature, possible overheating.':
        reason = '1、散热不良或环境温度高。\n2、设备内部灰尘积累或散热片故障。'
        action = action4
    else:
        reason = '运行正常。'
        action = action2

    return render(request, 'sysdata.html', locals())

def cpu(request):
    logical_core_num = psutil.cpu_count()
    physical_core_num = psutil.cpu_count(logical=False)
    load_avg = ['', '', '']
    cpu_time_percent = psutil.cpu_times_percent()
    else_percent = 0.0  # 空闲CPU占有率
    for i in range(3, 5):
        else_percent += cpu_time_percent[i]
    try:
        cpu_freq = psutil.cpu_freq()
    except AttributeError:
        cpu_freq = None
    return render(request, 'cpu.html', locals())


def memory_info_view(request):
    memory_info = psutil.virtual_memory()
    context = {
        'memory_info': memory_info,
    }
    return render(request, 'memory_usage.html', context)

def request_count_view(request):
    request_count = RequestCountMiddleware.request_count
    context = {
        'request_count': request_count,
    }
    return render(request, 'request_count.html', context)

def logout(request):
    return redirect("/index/")

def codeindex(request):
    return render(request, 'code_evaluate.html')

def submit(request):
    if request.method == 'POST':
        text_input = request.POST.get('textInput')
        file_input = request.FILES.get('fileInput')

        if text_input:
            with open('text.py', 'w', encoding='utf-8') as f:
                f.write("# -*- coding:utf-8 -*-")
                f.write(text_input)

        if file_input:
            fs = FileSystemStorage()
            filename = fs.save(file_input.name, file_input)
            file_url = fs.url(filename)
        else:
            file_url = '没有上传任何文件'

        str_lines = "not analysis"
        if file_input:
            if ".py" in file_url:
                modified_string = file_url[1:]
                cmd = "pylint " + modified_string
                out = os.popen(cmd)
                str_lines = out.readlines()
        if text_input:
            cmd = "pylint text.py"
            out = os.popen(cmd)
            str_lines = out.readlines()

        code_output_str = "\n".join(str_lines)
        return render(request, 'code_evaluate.html', {
            'text_output': text_input,
            'file_output': file_url,
            'code_output': code_output_str,
        })
    return HttpResponse("提交失败，请重试。")

def manage(request):
    conn = MySQLdb.connect(host="localhost", user="root", passwd=userpwd, db="project", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        cursor.execute(
            "SELECT LogID,LogType,OccurTime,SourceIP,userID,Content,Level,RelatedID,Status,Handler,HandleTime FROM sims_efflog")
        efflog = cursor.fetchall()

        cursor.execute("SELECT * FROM syslog LIMIT 1000")
        syslog = cursor.fetchall()
    return render(request, 'manage.html', {'efflog': efflog, 'syslog': syslog})

def logdel(request):
    LogID = request.GET.get("LogID")
    conn = MySQLdb.connect(host="localhost", user="root", passwd=userpwd, db="project", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        with transaction.atomic():
            cursor.execute("DELETE FROM sims_efflog WHERE LogID=%s;", [LogID])

            conn.commit()
    return redirect("/manage/")

def sysdel(request):
    LogID = request.GET.get("LogID")
    conn = MySQLdb.connect(host="localhost", user="root", passwd=userpwd, db="project", charset='utf8')
    with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:
        with transaction.atomic():
            cursor.execute("DELETE FROM syslog WHERE LogID=%s;", [LogID])
            conn.commit()
    return redirect("/manage/")

def edit(request):
    CPUusage=request.GET.get("CPUusage")
    return redirect("/sysdata/")

def limit(request):
    MEMusage=request.GET.get("MEMusage")
    return redirect("/sysdata/")

def unlockCPU(request):
    CPUusage = request.GET.get("CPUusage")
    return redirect("/sysdata/")

def unlockMEM(request):
    MEMusage=request.GET.get("MEMusage")
    return redirect("/sysdata/")

def control(request):
    automation_level = request.session.get('automation_level')
    decision_making = request.session.get('decision_making')
    ml_algorithm = request.session.get('ml_algorithm')
    a=''
    b=''
    c=''
    if request.method == 'POST':
        automation_level = request.POST.get('automation_level')
        decision_making = request.POST.get('decision_making')
        ml_algorithm = request.POST.get('ml_algorithm')
        messages.success(request, '设置成功')
        request.session['automation_level'] = automation_level
        request.session['decision_making'] = decision_making
        request.session['ml_algorithm'] = ml_algorithm
    if automation_level == 'low':
        a = '低智能化力度'
    elif automation_level == 'medium':
        a = '中智能化力度'
    else:
        a = '高智能化力度'
    if decision_making == 'decision_tree':
        b = '决策树算法'
    elif decision_making == 'Bayes':
        b = '朴素贝叶斯算法'
    else:
        b = '支持向量机算法'
    c = '正在使用机器学习决策算法'
    return render(request, 'control.html', locals())
